package com.miku.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.miku.blog.domain.Article;
import com.miku.blog.domain.Category;
import com.miku.blog.domain.pojo.ResponseResult;
import com.miku.blog.domain.pojo.SystemConstance;
import com.miku.blog.domain.dto.CategoryDTO;
import com.miku.blog.domain.vo.PageVo;
import com.miku.blog.eume.HttpStatusEnum;
import com.miku.blog.exception.SystemException;
import com.miku.blog.service.ArticleService;
import com.miku.blog.service.CategoryService;
import com.miku.blog.mapper.CategoryMapper;
import com.miku.blog.utils.BeanCopyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Lazy;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
* @author Miku
* @description 针对表【tb_category】的数据库操作Service实现
* @createDate 2022-05-26 18:34:31
*/
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category>
    implements CategoryService{

    @Lazy
    @Autowired
    private ArticleService articleService;

    @Override
    public ResponseResult categories(Integer current, Integer size,@Nullable String keywords) {

        Page<Category> page = new Page<>(current, size);
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.hasText(keywords),Category::getCategoryName,keywords)
                .orderByDesc(Category::getCreateTime);
        page(page,queryWrapper);
        List<Category> categoryList = page.getRecords();
        categoryList.stream()
                .peek(category -> {
                    long articleCount = articleService.getArticleCountByCategoryId(category.getId());
                    category.setArticleCount((int) articleCount);
                }).collect(Collectors.toList());
        PageVo<Category> pageVo = new PageVo<>(page.getTotal(),categoryList);
        return ResponseResult.ok().setData(pageVo);
    }


    @Override
    public ResponseResult addCategories(Category category) {
        if (!StringUtils.hasText(category.getCategoryName())){
            return new ResponseResult(HttpStatusEnum.PARAM_ERROR);
        }
        Integer categoryId = category.getId();
        if (Objects.isNull(categoryId)){
            //若ID 为NULL,则当前为新增分类
            if (Objects.nonNull(getCategoryByName(category.getCategoryName()))){
                return new ResponseResult(HttpStatusEnum.INSERT_CATEGORY_ERROR);
            }
//            category.setCreateTime(new Date());
            if (!save(category)) {
                return new ResponseResult(HttpStatusEnum.INSERT_DATA_ERROR);
            }
        }else {
            LambdaUpdateWrapper<Category> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(Category::getId,categoryId)
                    .set(Category::getCategoryName,category.getCategoryName());
            if (!update(updateWrapper)) {
                return new ResponseResult(HttpStatusEnum.UPDATE_DATA_ERROR);
            }
        }
        return ResponseResult.ok();
    }

    @Transactional
    @Override
    public ResponseResult deleteCategories(Integer[] categoryIdList) {

        for (Integer id : categoryIdList) {
            List<Article> articles = articleService.getArticleListByCategory(id,null,null);
            if (Objects.nonNull(articles) && articles.size() > 0) {
                throw new SystemException(HttpStatusEnum.DELETE_CATEGORY_ERROR);
            }
            if (!removeById(id)) {
                throw new SystemException(HttpStatusEnum.REMOVE_DATA_ERROR);
            }
        }
        return ResponseResult.ok();
    }

    @Override
    public ResponseResult getCategories(Integer current) {
        Page<Category> page = new Page<>(current,SystemConstance.PAGE_SIZE);
        page(page,null);
        List<CategoryDTO> categoryDTOS = BeanCopyUtils.copyListByType(page.getRecords(), CategoryDTO.class);
        categoryDTOS.stream()
                .peek(dto -> {
                    long articleCount = articleService.getArticleCountByCategory(dto.getId());
                    dto.setArticleCount((int) articleCount);
                })
                .collect(Collectors.toList());
        PageVo<CategoryDTO> pageVo = new PageVo<>(page.getTotal(),categoryDTOS);
        return ResponseResult.ok().setData(pageVo);
    }



    @Override
    public Category getCategoryByName(String categoryName){
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Category::getCategoryName,categoryName);
        return getOne(queryWrapper);
    }


    @Override
    public ResponseResult getCategoryList() {
        List<Category> categoryList = list();
        List<CategoryDTO> categoryDTOS = BeanCopyUtils.copyListByType(categoryList, CategoryDTO.class);
        return ResponseResult.ok().setData(categoryDTOS);
    }
}




